import { defineStore } from "pinia";
import { userLogin, getUserInfo } from "@/api/user/";
import type { LoginData, LoginResult } from "@/api/user/type";
import { constantRoute, asnycRoute } from "@/router/routes";

import cloneDeep from "lodash/cloneDeep";
import router from "@/router";
function filterAsyncRoute(asnycRoute: any, routes: any) {
	return asnycRoute.filter((item: any) => {
		if (routes.includes(item.name)) {
			if (item.children && item.children.length > 0) {
				//硅谷333账号:product\trademark\attr\sku
				item.children = filterAsyncRoute(item.children, routes);
			}
			return true;
		}
	});
}

export interface IUserStore {
	id: number;
	asscessToken: string;
	username: string;
	nickname: string;
	role: string;
	avatar: string;
	menuRoutes;
}

export const useUserStore = defineStore("user", {
	// 定义状态
	state: (): IUserStore => ({
		id: 1,
		asscessToken: "",
		username: "",
		nickname: "",
		role: "",
		avatar: "",
		menuRoutes: constantRoute, //仓库存储生成菜单需要数组(路由)
	}),
	// 计算属性
	getters: {},
	// 方法
	actions: {
		// 登录方法
		async storeUserLogin(data: LoginData) {
			// 登录逻辑
			const { data: res } = await userLogin(data);
			this.asscessToken = res.accessToken;
			return res as LoginResult;
		},
		// 获取用户信息方法
		async storeUserInfo() {
			try {
				const { data: res } = await getUserInfo();
				this.username = res.username;
				this.avatar = res.avatar;
				this.id = res.id;
				console.log(res.routes);
				//计算当前用户需要展示的异步路由
				const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), res.routes);
				console.log(userAsyncRoute);
				//菜单需要的数据整理完毕
				this.menuRoutes = [...constantRoute, ...userAsyncRoute];
				//目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
				[...userAsyncRoute].forEach((route: any) => {
					router.addRoute(route);
				});
				return res;
			} catch (error) {
				console.log("获取用户信息失败", error);
				return Promise.reject(error);
			}
		},

		// 退出登录
		async userLogout() {
			this.asscessToken = "";
			this.username = "";
		},
	},
	// 持久化配置
	persist: {
		key: "userInfo", // 存储到 localStorage 的 key
		storage: localStorage, // 存储方式
		pick: ["asscessToken", "avatar", "id"], // 需要持久化的状态字段
	},
});
